"""
库存管理服务
"""
import random
import logging
from datetime import datetime, timedelta
from config import get_config
from .data_generator import DataGenerator

config = get_config()
logger = logging.getLogger(__name__)


class InventoryService:
    """库存管理服务类"""

    @staticmethod
    def query_stocks_by_condition(data: dict) -> list:
        """现存量查询（用友标准接口）"""
        # 解析查询参数（支持单个或批量）
        def to_list(value):
            """统一转换为列表格式"""
            if value is None:
                return []
            if isinstance(value, list):
                return value
            return [value]

        # 提取查询条件
        orgs = to_list(data.get('org'))
        warehouses = to_list(data.get('warehouse'))
        warehouse_codes = to_list(data.get('warehouse.code'))
        products = to_list(data.get('product'))
        product_codes = to_list(data.get('productn.code'))
        productskus = to_list(data.get('productsku'))
        productsku_codes = to_list(data.get('productsku.code'))  # 新增：SKU编码查询
        batchnos = to_list(data.get('batchno'))
        stock_status_docs = to_list(data.get('stockStatusDoc'))
        b_stock_status_not_null = data.get('bStockStatusDocNotNull', False)
        billnum = data.get('billnum')  # 可用量计算规则

        # 优先使用真实ERP数据，如果不存在则生成模拟数据
        import os
        import json
        project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        erp_data_path = os.path.join(project_root, "data", "inventory_records_50.json")

        if os.path.exists(erp_data_path):
            try:
                with open(erp_data_path, "r", encoding="utf-8") as f:
                    all_inventory_items = json.load(f)
                logger.info(f"使用真实ERP库存数据: {len(all_inventory_items)}条记录")
            except Exception as e:
                logger.warning(f"读取真实ERP数据失败: {str(e)}，使用模拟数据")
                all_inventory_items = DataGenerator.generate_inventory_items(count=85)
        else:
            # 生成库存数据（总共85条）
            all_inventory_items = DataGenerator.generate_inventory_items(count=85)
            logger.info("使用模拟库存数据")

        # 过滤数据
        result_items = []
        for item in all_inventory_items:
            # 判断数据格式：真实ERP数据已经是用友格式，模拟数据需要转换
            is_erp_format = "currentqty" in item  # 真实ERP数据包含currentqty字段

            # 组织过滤（兼容两种格式）
            org_value = item.get("org") if is_erp_format else item.get("org_id")
            if orgs and org_value not in orgs:
                continue

            # 仓库过滤（ID或编码）
            warehouse_value = item.get("warehouse") if is_erp_format else item.get("warehouse_id")
            if warehouses and warehouse_value not in warehouses:
                continue
            if warehouse_codes and item.get("warehouse_code") not in warehouse_codes:
                continue

            # 物料过滤（ID或编码）
            product_value = item.get("product") if is_erp_format else item.get("material_id")
            if products and product_value not in products:
                continue
            product_code_value = item.get("product_code") if is_erp_format else item.get("material_code")
            if product_codes and product_code_value not in product_codes:
                continue

            # SKU过滤（ID或编码）
            productsku_value = item.get("productsku") if is_erp_format else item.get("productsku_id")
            if productskus and productsku_value not in productskus:
                continue
            if productsku_codes and item.get("productsku_code") not in productsku_codes:
                continue

            # 批次号过滤
            batchno_value = item.get("batchno") if is_erp_format else item.get("batch_no")
            if batchnos and batchno_value not in batchnos:
                continue

            # 库存状态过滤
            stock_status_value = item.get("stockStatusDoc") if is_erp_format else item.get("stock_status_doc")
            if stock_status_docs and stock_status_value not in stock_status_docs:
                continue

            # 库存状态非空过滤
            if b_stock_status_not_null and (not stock_status_value or stock_status_value == 0):
                continue

            # 如果是真实ERP数据，直接返回（已经是用友标准格式）
            if is_erp_format:
                result_items.append(item)
                continue

            # 如果是模拟数据，需要转换为用友标准格式
            # 构建用友标准返回格式（18个核心字段）
            current_qty = item["current_stock"]
            reserved_qty = item.get("reserved_stock", 0)
            in_notice_qty = random.randint(0, 200)  # 预计入库数量
            pre_retail_qty = reserved_qty  # 预计出库数量

            # 可用量计算规则（根据billnum参数）
            available_qty = InventoryService._calculate_available_qty(
                current_qty, reserved_qty, in_notice_qty, pre_retail_qty, billnum
            )

            # 计划可用量
            plan_available_qty = current_qty + in_notice_qty - pre_retail_qty

            result_item = {
                # 1. 组织信息
                "org": item.get("org_id", "1891127153005312"),

                # 2. 仓库信息
                "warehouse": item["warehouse_id"],

                # 3-5. 物料基本信息
                "product": item["material_id"],
                "product_name": item["material_name"],
                "product_code": item["material_code"],

                # 6-8. SKU信息
                "productsku": item.get("productsku_id", item["material_id"]),
                "productsku_name": item.get("productsku_name", item["material_name"]),
                "productsku_code": item.get("productsku_code", item["material_code"]),

                # 9-11. 物料分类
                "manageClass": item.get("manage_class_id", "2000100011111111"),
                "manageClass_code": item.get("manage_class_code", "YCL_001"),
                "manageClass_name": item.get("manage_class_name", "原材料类"),

                # 12. 计量单位
                "unit": item.get("unit_id", "1921568854316953"),

                # 13-18. 核心库存数量
                "currentqty": current_qty,  # 现存量 ⭐
                "availableqty": available_qty,  # 可用量 ⭐ (根据规则计算)
                "innoticeqty": in_notice_qty,  # 收货预计入库数量
                "planavailableqty": plan_available_qty,  # 计划可用量
                "preretailqty": pre_retail_qty,  # 订单预计出库数量
                "stockStatusDoc": item.get("stock_status_doc", 2006555827382257),  # 库存状态

                # 19-22. 批次信息（扩展字段）
                "batchno": item.get("batch_no"),  # 批次号
                "productionDate": item.get("production_date"),  # 生产日期
                "expiryDate": item.get("expiry_date"),  # 有效期至
                "batchStatus": item.get("batch_status")  # 批次状态
            }

            result_items.append(result_item)

        logger.info(f"现存量查询完成: 符合条件的记录数={len(result_items)}, billnum={billnum}")
        return result_items

    @staticmethod
    def _calculate_available_qty(current_qty, reserved_qty, in_notice_qty, pre_retail_qty, billnum):
        """
        根据单据类型计算可用量

        参数：
            current_qty: 现存量
            reserved_qty: 预留数量
            in_notice_qty: 预计入库数量
            pre_retail_qty: 预计出库数量
            billnum: 单据类型

        返回：
            计算后的可用量
        """
        # 基础可用量（默认规则）
        base_available = current_qty - reserved_qty

        # 如果没有指定billnum，使用默认规则
        if not billnum:
            return base_available

        # 根据不同单据类型应用不同规则
        billnum_rules = {
            # 销售订单：现存量 - 预留量
            "voucher_order": base_available,

            # 销售发货：现存量 - 预留量 - 待发量
            "voucher_delivery": base_available - int(reserved_qty * 0.5),

            # 电商订单：现存量 - 预留量 - 电商占用
            "ec_tradeorder_add": base_available - int(reserved_qty * 0.3),

            # 调拨订单：现存量 - 所有占用
            "st_transferapply": current_qty - reserved_qty - pre_retail_qty,

            # 采购订单：现存量 + 预计入库 - 预计出库
            "st_purchaseorder": current_qty + in_notice_qty - pre_retail_qty,

            # 出库申请单：现存量
            "po_picking_requisition": current_qty,

            # 其他出库单：现存量 - 预留量
            "st_othoutrecord": base_available
        }

        # 获取对应规则的可用量
        available = billnum_rules.get(billnum, base_available)

        # 确保可用量不为负
        return max(0, available)

    @staticmethod
    def process_material_outbound(data: dict) -> dict:
        """处理材料出库 - 符合用友API规范"""

        # 从API规范格式中提取信息
        source_id = data['materOuts'][0]['sourceid']  # 上游单据主表ID
        mater_outs = data['materOuts']

        # 生成出库单信息
        outbound_id = f"OUT{datetime.now().strftime('%Y%m%d')}{str(random.randint(1000, 9999))}"
        outbound_code = f"MO-{outbound_id}"

        # 生成真实的库存数据用于检查
        inventory_items = DataGenerator.generate_inventory_items(count=50)
        inventory_map = {item["material_code"]: item for item in inventory_items}

        # 处理每个物料出库明细
        processed_mater_outs = []
        stock_check_results = []

        for i, mater_out in enumerate(mater_outs):
            # 提取物料信息
            material_code = mater_out.get('productsku') or mater_out.get('product')
            if not material_code:
                # 尝试从库存数据中获取
                for item in inventory_items:
                    if item["material_id"] == mater_out.get('product'):
                        material_code = item["material_code"]
                        break

            required_qty = float(mater_out.get('qty', 0))

            # 从库存数据中查找对应物料
            inventory_item = None
            for item in inventory_items:
                if (item["material_code"] == material_code or
                    item["material_id"] == mater_out.get('product')):
                    inventory_item = item
                    break

            if inventory_item:
                available_stock = inventory_item["available_stock"]
                material_name = inventory_item["material_name"]
                material_id = inventory_item["material_id"]
            else:
                # 如果没有找到，生成一个合理的库存数量
                available_stock = random.randint(100, 3000)
                material_name = f"物料{material_code}"
                material_id = f"MAT{material_code}"

            # 库存检查结果
            can_fulfill = available_stock >= required_qty
            stock_check_result = {
                "material_id": material_id,
                "material_code": material_code,
                "material_name": material_name,
                "required_quantity": required_qty,
                "available_stock": available_stock,
                "shortage": max(0, required_qty - available_stock),
                "can_fulfill": can_fulfill
            }
            stock_check_results.append(stock_check_result)

            # 构建符合API规范的返回格式
            processed_mater_out = {
                "id": random.randint(1000000, 9999999),  # 子表主键ID
                "mainid": random.randint(1000000, 9999999),  # 主表ID
                "product": mater_out.get('product', ''),
                "productsku": mater_out.get('productsku', ''),
                "product_code": material_code,
                "product_name": material_name,
                "qty": required_qty,
                "stockUnitId": mater_out.get('stockUnitId', '1921568854316953'),  # 库存单位ID
                "stockUnit_name": "件",
                "unit": mater_out.get('unit', '1921568854316953'),  # 主计量ID
                "unit_Precision": "0",
                "invExchRate": 1,
                "sourceid": mater_out.get('sourceid'),
                "sourceautoid": mater_out.get('sourceautoid'),
                "sourceGrandchildrenId": mater_out.get('sourceGrandchildrenId'),
                "makeRuleCode": mater_out.get('makeRuleCode'),
                "materialReqType": mater_out.get('materialReqType', 0),
                "batchno": mater_out.get('batchno'),
                "producedate": mater_out.get('producedate'),
                "goodsposition": mater_out.get('goodsposition'),
                "memo": mater_out.get('memo', ''),
                "lineno": i + 1,  # 行号
                "isBatchManage": bool(mater_out.get('batchno')),
                "isSerialNoManage": bool(mater_out.get('materOutsSNs')),
                "isExpiryDateManage": bool(mater_out.get('producedate')),
                "supplyType": mater_out.get('supplyType', ''),
                "stockStatusDoc": random.randint(2006555827382256, 2006555827382258),  # 库存状态
                "stockStatusDoc_name": "正常",
                "inventoryowner": random.randint(1000000, 9999999),  # 货主对象
                "ownertype": 1,
                "reserveid": random.randint(1000000, 9999999),  # 预留对象ID
                "subQty": int(required_qty),  # 件数
                "contactsQuantity": required_qty,  # 应发数量
                "contactsPieces": int(required_qty),  # 应发件量
                "isUpdateCost": True,
                "isScrap": False,
                "firstsource": mater_out.get('makeRuleCode', ''),
                "firstsourceid": mater_out.get('sourceid'),
                "firstsourceautoid": mater_out.get('sourceautoid'),
                "firstsourceGrandchildrenId": mater_out.get('sourceGrandchildrenId'),
                "firstupcode": f"MO-{source_id}",
                "firstlineno": i + 1,
                "source": "生产订单",
                "upcode": f"MO-{source_id}",
                "uplineno": i + 1,
                "sourceOrderlineno": i + 1,
                "productsku_cCode": material_code,
                "productsku_cName": material_name,
                "product_cCode": material_code,
                "product_cName": material_name,
                "pubts": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }

            processed_mater_outs.append(processed_mater_out)

        # 模拟成功率
        is_success = random.random() > (1 - config.MOCK_SUCCESS_RATE)

        if is_success:
            # 记录出库流水
            transaction_records = []
            for i, mater_out in enumerate(mater_outs):
                stock_result = stock_check_results[i]
                if stock_result['can_fulfill']:  # 只记录成功出库的物料
                    try:
                        transaction_data = {
                            'material_id': stock_result['material_id'],
                            'material_code': stock_result['material_code'],
                            'transaction_type': 'PRODUCTION_OUT',
                            'quantity': stock_result['required_quantity'],
                            'reason': '生产出库',
                            'reference_doc': 'MO',
                            'reference_id': source_id,
                            'operator': '生产操作员',
                            'department': '生产部',
                            'remarks': f"订单{source_id}生产出库"
                        }
                        transaction_record = InventoryService.record_inventory_transaction(transaction_data)
                        transaction_records.append(transaction_record)
                    except Exception as e:
                        logger.warning(f"记录库存流水失败: {str(e)}")

            # 构建符合用友API规范的返回数据
            current_time = datetime.now()
            org_id = "1891127153005312"  # 默认库存组织ID

            return {
                "code": "200",
                "message": "",
                "data": {
                    "id": random.randint(1000000000000000, 9999999999999999),  # 主表主键ID
                    "org": org_id,
                    "org_name": "生产组织",
                    "factoryFiOrg": org_id,
                    "factoryFiOrg_name": "生产组织",
                    "accountOrg": org_id,
                    "accountOrg_name": "生产组织",
                    "factoryOrg": org_id,
                    "factory_name": "生产组织",
                    "code": outbound_code,
                    "isOsm": False,
                    "warehouse_isGoodsPositionStock": False,
                    "srcBill": source_id,
                    "materialOutType": "生产出库",
                    "isWfControlled": False,
                    "srcBillNO": f"MO-{source_id}",
                    "warehouse": processed_mater_outs[0].get('warehouse', 'WH001'),
                    "srcBillType": "生产订单",
                    "warehouse_countCost": True,
                    "barCode": f"BAR{outbound_id}",
                    "warehouse_name": "原材料仓库",
                    "vouchtype": random.randint(2000000000000000, 2999999999999999),  # 单据类型
                    "inventoryowner": org_id,
                    "isUpdateCost": True,
                    "status": 1,  # 已提交
                    "verifystate": 0,  # 未审核
                    "shop": org_id,
                    "extend_attrs_json": "{}",
                    "creatorId": random.randint(1000000, 9999999),
                    "vouchdate": data.get('vouchdate', current_time.strftime('%Y-%m-%d %H:%M:%S')),
                    "warehouse_isGoodsPosition": False,
                    "department": "生产部",
                    "pubts": current_time.strftime('%Y-%m-%d %H:%M:%S'),
                    "createDate": current_time.strftime('%Y-%m-%d'),
                    "creator": "系统用户",
                    "department_name": "生产部",
                    "warehouse_iSerialManage": False,
                    "bustype": data.get('bustype', '2000000000000000'),
                    "createTime": current_time.strftime('%H:%M:%S'),
                    "ownertype": 1,
                    "headItem": {
                        "id": str(random.randint(1000000000000000, 9999999999999999)),
                        "define1": ""
                    },
                    "defines": {
                        "id": str(random.randint(1000000000000000, 9999999999999999)),
                        "define1": ""
                    },
                    "materOuts": processed_mater_outs,
                    "submit_time": current_time.isoformat(),
                    "expected_delivery_time": (current_time + timedelta(hours=2)).isoformat(),
                    "stock_check_results": stock_check_results,
                    "total_materials": len(mater_outs),
                    "can_fulfill_all": all(r['can_fulfill'] for r in stock_check_results),
                    "transaction_records": transaction_records
                }
            }
        else:
            raise Exception("库存系统暂时不可用")

    @staticmethod
    def query_inventory(material_code: str, warehouse_id: str, page: int, page_size: int) -> dict:
        """查询库存信息"""
        # 使用数据生成器生成真实的库存数据
        all_inventory_items = DataGenerator.generate_inventory_items(count=85)

        # 根据查询条件过滤
        filtered_items = []
        for item in all_inventory_items:
            if material_code and material_code not in item["material_code"]:
                continue
            if warehouse_id and item["warehouse_id"] != warehouse_id:
                continue
            filtered_items.append(item)

        # 分页处理
        total_items = len(filtered_items)
        start_idx = (page - 1) * page_size
        end_idx = min(start_idx + page_size, total_items)

        inventory_items = []
        for i in range(start_idx, end_idx):
            item = filtered_items[i]
            # 添加额外的库存相关字段
            current_stock = item["current_stock"]
            available_stock = item["available_stock"]

            inventory_items.append({
                "material_id": item["material_id"],
                "material_code": item["material_code"],
                "material_name": item["material_name"],
                "material_type": "原材料",
                "specification": f"规格{item['material_code'][-3:]}",
                "unit": item["unit"],
                "warehouse_id": item["warehouse_id"],
                "warehouse_name": item["warehouse_name"],
                "location_id": f"LOC{str(random.randint(1, 20)).zfill(3)}",
                "location_name": f"货位{random.randint(1, 20)}",
                "current_stock": current_stock,
                "available_stock": available_stock,
                "reserved_stock": item["reserved_stock"],
                "in_transit_stock": random.randint(0, 100),
                "safety_stock": item["safety_stock"],
                "reorder_point": int(item["safety_stock"] * 1.5),
                "last_in_date": item["last_in_date"],
                "last_out_date": item["last_out_date"],
                "last_update_time": datetime.now().isoformat(),
                "stock_status": "normal" if available_stock > item["safety_stock"] else "low" if available_stock > item["safety_stock"] * 0.5 else "critical",
                "batch_no": f"BATCH{datetime.now().strftime('%Y%m')}{str(random.randint(100, 999))}",
                "expire_date": (datetime.now() + timedelta(days=random.randint(90, 365))).isoformat()
            })

        # 计算库存状态统计
        normal_count = sum(1 for item in filtered_items if item["current_stock"] > item["safety_stock"])
        low_count = sum(1 for item in filtered_items if item["safety_stock"] * 0.5 < item["current_stock"] <= item["safety_stock"])
        critical_count = sum(1 for item in filtered_items if item["current_stock"] <= item["safety_stock"] * 0.5)

        return {
            "total": total_items,
            "page": page,
            "page_size": page_size,
            "pages": (total_items + page_size - 1) // page_size,
            "items": inventory_items,
            "summary": {
                "total_materials": total_items,
                "low_stock_count": low_count,
                "critical_stock_count": critical_count,
                "normal_stock_count": normal_count
            }
        }

    @staticmethod
    def record_inventory_transaction(transaction_data: dict) -> dict:
        """记录库存流水"""
        required_fields = ['material_id', 'material_code', 'transaction_type', 'quantity']
        for field in required_fields:
            if not transaction_data.get(field):
                raise ValueError(f"{field}不能为空")

        transaction_id = f"TRX{datetime.now().strftime('%Y%m%d%H%M%S')}{str(random.randint(1000, 9999))}"

        # 获取物料信息
        inventory_items = DataGenerator.generate_inventory_items(count=20)
        material_info = None
        for item in inventory_items:
            if item['material_id'] == transaction_data['material_id'] or item['material_code'] == transaction_data['material_code']:
                material_info = item
                break

        if not material_info:
            # 如果没有找到物料信息，创建一个默认值
            material_info = {
                'material_name': '未知物料',
                'unit': '件',
                'warehouse_id': 'WH01',
                'warehouse_name': '默认仓库'
            }

        transaction_types = {
            'IN': '入库',
            'OUT': '出库',
            'TRANSFER': '转移',
            'ADJUSTMENT': '调整',
            'PRODUCTION_IN': '生产入库',
            'PRODUCTION_OUT': '生产出库',
            'SALES_OUT': '销售出库',
            'PURCHASE_IN': '采购入库'
        }

        # 模拟流水记录
        current_stock = random.randint(100, 5000)
        transaction_qty = abs(transaction_data['quantity'])  # 确保数量为正数

        # 根据事务类型计算库存变化
        if transaction_data['transaction_type'] in ['OUT', 'PRODUCTION_OUT', 'SALES_OUT']:
            new_stock = max(0, current_stock - transaction_qty)
            available_stock = new_stock
        elif transaction_data['transaction_type'] in ['IN', 'PURCHASE_IN', 'PRODUCTION_IN']:
            new_stock = current_stock + transaction_qty
            available_stock = new_stock
        else:  # TRANSFER, ADJUSTMENT
            new_stock = current_stock
            available_stock = current_stock

        return {
            "transaction_id": transaction_id,
            "transaction_code": f"IV-{transaction_id}",
            "transaction_type": transaction_data['transaction_type'],
            "transaction_type_name": transaction_types.get(transaction_data['transaction_type'], '未知类型'),
            "transaction_time": datetime.now().isoformat(),
            "material_id": transaction_data['material_id'],
            "material_code": transaction_data['material_code'],
            "material_name": material_info['material_name'],
            "unit": material_info['unit'],
            "warehouse_id": material_info['warehouse_id'],
            "warehouse_name": material_info['warehouse_name'],
            "quantity": transaction_qty,
            "current_stock": current_stock,
            "new_stock": new_stock,
            "available_stock": available_stock,
            "transaction_reason": transaction_data.get('reason', '正常业务'),
            "reference_doc": transaction_data.get('reference_doc', ''),
            "reference_id": transaction_data.get('reference_id', ''),
            "operator": transaction_data.get('operator', '系统用户'),
            "department": transaction_data.get('department', '生产部'),
            "cost_center": transaction_data.get('cost_center', 'CC001'),
            "batch_no": transaction_data.get('batch_no', f"BATCH{datetime.now().strftime('%Y%m')}{random.randint(100, 999)}"),
            "remarks": transaction_data.get('remarks', ''),
            "created_by": transaction_data.get('created_by', 'system'),
            "created_time": datetime.now().isoformat()
        }

    @staticmethod
    def query_inventory_transactions(query_params: dict) -> dict:
        """查询库存流水记录"""
        page = query_params.get('page', 1)
        page_size = query_params.get('page_size', 20)
        material_code = query_params.get('material_code', '')
        warehouse_id = query_params.get('warehouse_id', '')
        transaction_type = query_params.get('transaction_type', '')
        start_date = query_params.get('start_date')
        end_date = query_params.get('end_date')

        # 生成模拟流水数据
        total_records = 156
        transactions = []

        transaction_types = {
            'IN': '入库', 'OUT': '出库', 'TRANSFER': '转移', 'ADJUSTMENT': '调整',
            'PRODUCTION_IN': '生产入库', 'PRODUCTION_OUT': '生产出库',
            'SALES_OUT': '销售出库', 'PURCHASE_IN': '采购入库'
        }

        # 获取物料信息用于生成真实数据
        inventory_items = DataGenerator.generate_inventory_items(count=15)

        # 计算实际需要生成的记录数
        start_idx = (page - 1) * page_size
        end_idx = min(start_idx + page_size, total_records)
        records_to_generate = max(0, end_idx - start_idx)

        for i in range(records_to_generate):
            # 随机选择物料
            material = random.choice(inventory_items)
            trx_type = random.choice(list(transaction_types.keys()))

            # 生成合理的数量
            if trx_type in ['OUT', 'PRODUCTION_OUT', 'SALES_OUT']:
                quantity = random.randint(10, 500) * -1  # 出库为负
            else:
                quantity = random.randint(10, 500)  # 入库为正

            current_stock = random.randint(200, 5000)
            new_stock = current_stock + quantity

            transactions.append({
                "transaction_id": f"TRX{datetime.now().strftime('%Y%m%d')}{str(random.randint(100000, 999999))}",
                "transaction_code": f"IV-{random.randint(10000, 99999)}",
                "transaction_type": trx_type,
                "transaction_type_name": transaction_types[trx_type],
                "transaction_time": (datetime.now() - timedelta(days=random.randint(0, 30), hours=random.randint(0, 23))).isoformat(),
                "material_id": material['material_id'],
                "material_code": material['material_code'],
                "material_name": material['material_name'],
                "unit": material['unit'],
                "warehouse_id": material['warehouse_id'],
                "warehouse_name": material['warehouse_name'],
                "quantity": quantity,
                "current_stock": current_stock,
                "new_stock": new_stock,
                "available_stock": new_stock - random.randint(0, int(new_stock * 0.1)),
                "transaction_reason": random.choice(['正常业务', '生产需求', '销售出库', '采购入库', '库存调整']),
                "reference_doc": random.choice(['MO', 'PO', 'SO', 'ADJ']),
                "reference_id": f"{random.choice(['MO', 'PO', 'SO', 'ADJ'])}-{random.randint(10000, 99999)}",
                "operator": random.choice(['张操作员', '李操作员', '王操作员', '赵操作员']),
                "department": random.choice(['生产部', '仓储部', '质检部']),
                "cost_center": f"CC{random.randint(1, 5):03d}",
                "batch_no": f"BATCH{datetime.now().strftime('%Y%m')}{random.randint(100, 999)}",
                "remarks": random.choice(['正常操作', '紧急补料', '质量检验', '定期盘点']),
                "created_by": 'system',
                "created_time": datetime.now().isoformat()
            })

        # 计算汇总信息
        total_in_quantity = sum(t['quantity'] for t in transactions if t['quantity'] > 0)
        total_out_quantity = sum(abs(t['quantity']) for t in transactions if t['quantity'] < 0)

        transaction_stats = {}
        for trx in transactions:
            trx_type = trx['transaction_type_name']
            if trx_type not in transaction_stats:
                transaction_stats[trx_type] = 0
            transaction_stats[trx_type] += 1

        return {
            "total": total_records,
            "page": page,
            "page_size": page_size,
            "pages": (total_records + page_size - 1) // page_size,
            "transactions": transactions,
            "summary": {
                "total_transactions": total_records,
                "total_in_quantity": total_in_quantity,
                "total_out_quantity": total_out_quantity,
                "net_change": total_in_quantity - total_out_quantity,
                "transaction_stats": transaction_stats,
                "date_range": {
                    "start_date": (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'),
                    "end_date": datetime.now().strftime('%Y-%m-%d')
                }
            }
        }